$p = {
	loadPrerequisites : function(arg) {
		$store.get({
			url : '/admin/product/load/prerequisite',
			data : null,
			success : function(data) {
				arg.loadComplete(data);
			},
			error : function(e) {
				alert('failed to load prerequisites');
			}
		});
	},
	loadProducts : function(arg) {
		$store.get({
			url : '/admin/product/load',
			data : null,
			success : function(data) {
				arg.loadComplete(data);
			},
			error : function(e) {
				alert('failed to load prerequisites');
			}
		});
	},
	loadVariations : function(arg) {
		$store.get({
			url : '/admin/product/load/variation',
			data : JSON.stringify({
				categoryId : arg.categoryId
			}),
			success : function(data) {
				arg.loadComplete(data);
			},
			error : function(e) {
				alert('failed to load variations');
			}
		});
	},
	save : function(arg) {
		console.log(arg.data);
		// return;
		$store.postJson({
			url : '/admin/product/save',
			data : arg.data,
			success : function(d) {
				arg.saveComplete();
			},
			error : function(e) {
				alert('failed to save products');
			}
		});
	},
	categoryCheckboxClick : function(eventData) {
		var checkbox = eventData.control;
		var varField = $('#variation-list');
		var checkboxes = varField.find('input:checkbox[data-parent-id="'
				+ eventData.id + '"]');
		if (checkbox.is(':checked')) {
			if (checkboxes.length == 0) {
				$p.loadVariations({
					categoryId : eventData.id,
					loadComplete : function(data) {
						var variations = data.variations;
						var template = $('#list-template');
						if (variations.length == 0)
							return;
						for ( var i = 0; i < variations.length; i++) {
							var variation = variations[i];
							var item = template.clone();
							item.children('label').text(variation.name);
							var checkbox = item.children('input:checkbox');
							checkbox.attr('value', variation.id).attr(
									'data-parent-id', eventData.id);
							item.appendTo(varField);
						}
						varField.find(
								'div > input:checkbox[data-parent-id="'
										+ eventData.id + '"]').fadeIn();
					}
				});
			} else {
				checkboxes.each(function() {
					$(this).closest('div').fadeIn();
				});
			}

		} else {
			checkboxes.each(function() {
				$(this).closest('div').hide();
			});
		}
	},
	prerequisiteLoadComplete : function(data) {
		var brands = data.brands;
		var categories = data.categories;
		var brandsField = $('#brand-list');
		for ( var i = 0; i < brands.length; i++) {
			var brand = brands[i];
			var fieldItem = $('<option/>');
			fieldItem.attr('value', brand.id);
			fieldItem.text(brand.name);
			fieldItem.appendTo(brandsField);
		}

		var catField = $('#category-list');
		var template = $('#list-template');
		for ( var i = 0; i < categories.length; i++) {
			var category = categories[i];
			var item = template.clone();
			item.children('label').text(category.name);
			var checkbox = item.children('input:checkbox');
			checkbox.attr('value', category.id);
			checkbox.bind('click', {
				id : category.id,
				control : checkbox
			}, function(e) {
				$p.categoryCheckboxClick(e.data);
			});
			item.appendTo(catField);
		}
		catField.find('div').fadeIn();
	},
	productLoadComplete : function(d) {
		if (d == null)
			return;
		// refresh the table
		$('#product-table').remove();

		var table = $('#table-template').clone();
		table.attr('id', 'product-table');
		table.css('display', 'block').appendTo('#page-root');
		for ( var i = 0; i < d.length; i++) {
			var c = d[i];
			var row = table.find('tr.store-row:first').clone();
			row.removeClass('hide');
			table.append(row);
			row.find('td::nth-child(1)').text(c.id);
			row.find('td:nth-child(2)').text(c.name);
			row.find('td:nth-child(3)').text(c.shortDescription);
			row.find('td:nth-child(4)').text(c.costPrice);
		}
		table.find('tr:odd').css('background-color', '#cabcab');
	}
}
$(document).ready(function() {
	$p.loadPrerequisites({
		loadComplete : function(data) {
			$p.prerequisiteLoadComplete(data);
		}
	});
	$p.loadProducts({
		loadComplete : function(d) {
			$p.productLoadComplete(d);
		}
	});
	$('#save-button').click(function() {
		$p.save({
			data : JSON.stringify({
				name : $('#name').val(),
				shortDescription : $('#desc').val(),
				longDescription : $('#long-desc').val(),
				costPrice : $('#price').val(),
				brandId : $('#brand-list').val(),
				categoryIds : $store.getCheckedValues('#category-list'),
				variationIds : $store.getCheckedValues('#variation-list'),
				unitsInStock : $('#sku').val()
			}),
			saveComplete : function() {
				$p.loadProducts({
					loadComplete : function() {
						$p.productLoadComplete(d);
					}
				});
			}
		});
	});
});